package cn.szzsi.service;

import cn.szzsi.common.model.CustomerAllowance;
import cn.szzsi.common.model.Member;
import cn.szzsi.common.model.Orders;
import cn.szzsi.common.model.SiteConfig;
import com.jfinal.plugin.activerecord.Db;
import com.jfinal.plugin.activerecord.Record;

import java.math.BigDecimal;
import java.util.*;

/**
 * 处理辅导津贴业务
 * Created by zhengy on 2017/2/21.
 */
public class AllowanceService {
    public static final AllowanceService ds=new AllowanceService();

    //获取辅导津贴列表(admin)
    public Map<String,Object> getFdjtList(Integer memberLevel, String uid){
        Map<String,Object> result = new HashMap<String,Object>();
        List<Record> lr = Db.find("select m.code,m.username,m.phone,b.*  from mall_member m right join mall_customer_allowance b on m.id=b.mid where b.memberLevel=? and b.uid=? order by b.createDate desc",memberLevel,uid);
        result.put("data",lr);
        result.put("rewardNum",lr.size());//分红人数

        SiteConfig siteConfig= SiteConfig.dao.findByShopId(uid);
        Integer orderPercent= siteConfig.getInt("orderPercent"+memberLevel);
        result.put("orderPercent",orderPercent);//分成比例

        //获取所选当天的营业额(totalAmount)
        /*Orders orders=new Orders();
        String profitDateEnd=profitDateEnd(profitDate);//截止到分红当天凌晨加上24小时之后的时间
        orders=orders.findFirst("select sum(totalAmount) totalAmount from mall_orders where paymentStatus='2' and uid=? and createDate>? and createDate<=?",uid,profitDate,profitDateEnd);
        BigDecimal totalAmount=orders.getBigDecimal("totalAmount");
        if(totalAmount==null){
            totalAmount=new BigDecimal(0);
        }*/
        /*result.put("totalAmount",totalAmount);//近日营业额
        result.put("rewardCash",totalAmount.multiply(new BigDecimal(rewardPercent).divide(new BigDecimal(100))));//分红金额*/
        return result;
    }

    //web
    public void createProfit(String uid, Orders orders, Member member){
        SiteConfig siteConfig= SiteConfig.dao.findByShopId(uid);//查询店铺配置信息
        BigDecimal totalIncome1=new BigDecimal(siteConfig.getInt("totalIncome1")*10000);//单位万
        BigDecimal totalIncome2=new BigDecimal(siteConfig.getInt("totalIncome2")*10000);
        BigDecimal totalIncome3=new BigDecimal(siteConfig.getInt("totalIncome3")*10000);
        BigDecimal totalIncome4=new BigDecimal(siteConfig.getInt("totalIncome4")*10000);
        BigDecimal totalIncome5=new BigDecimal(siteConfig.getInt("totalIncome5")*10000);
        BigDecimal totalIncome6=new BigDecimal(siteConfig.getInt("totalIncome6")*10000);

        BigDecimal orderPercent1=new BigDecimal(siteConfig.getInt("orderPercent1")).divide(new BigDecimal(100));
        BigDecimal orderPercent2=new BigDecimal(siteConfig.getInt("orderPercent2")).divide(new BigDecimal(100));
        BigDecimal orderPercent3=new BigDecimal(siteConfig.getInt("orderPercent3")).divide(new BigDecimal(100));
        BigDecimal orderPercent4=new BigDecimal(siteConfig.getInt("orderPercent4")).divide(new BigDecimal(100));
        BigDecimal orderPercent5=new BigDecimal(siteConfig.getInt("orderPercent5")).divide(new BigDecimal(100));
        BigDecimal orderPercent6=new BigDecimal(siteConfig.getInt("orderPercent6")).divide(new BigDecimal(100));

        String pid=member.getStr("pid");//上级会员id
        String pids=member.getStr("pids");//所有上级字符串
        List<String> list=new ArrayList();
        String pidsArray[];
        if(!"0".equals(pids)){//
            pidsArray=pids.split(",");//字符串转换为数组
            String reservePidsArray[]=new String[pidsArray.length];
            for(int i=0;i<pidsArray.length;i++){//将所有上级数据倒叙排列
                reservePidsArray[i]=pidsArray[pidsArray.length-1-i];
            }
            list=new ArrayList(Arrays.asList(reservePidsArray));//数组转换为集合(该集合存放的是所有上级id,并且按照推荐先后顺序排列)
        }

        int fdjtPercent=siteConfig.getInt("fdjtPercent");//辅导津贴百分比
        BigDecimal productTotalPrice=orders.getBigDecimal("productTotalPrice");//该订单的总金额
        String orderSn=orders.getStr("orderSn");//订单编号
        BigDecimal profit=new BigDecimal(0);//分成金额

        for(String memberId:list){//遍历所有上级id
            Member pMember= Member.dao.findById(memberId);//上级会员信息
            BigDecimal totaIncome=getTotalIncome(memberId);//上级会员总收入
            int memberLevel=0;//会员级别
            //查看是否是正式会员(针对开元一通)
            if(!"dafc86f6aee04a8aa9c722689ef65b3y".equals(pMember.getStr("memberRankId"))){
                continue;//如果上级不是正式会员,结束本次循环,进行下一轮循环
            }
            if(totaIncome.compareTo(totalIncome6)>=0 && fdjtPercent>0){
                if(fdjtPercent>=siteConfig.getInt("orderPercent6")){
                    profit=productTotalPrice.multiply(orderPercent6);
                    fdjtPercent=fdjtPercent-siteConfig.getInt("orderPercent6");
                }else{
                    profit=productTotalPrice.multiply(new BigDecimal(fdjtPercent));
                    fdjtPercent=0;
                }
                memberLevel=6;
                //Allowance.saveInfo(memberId,totaIncome,profit,0,1,orderSn,uid);
            }else if(totaIncome.compareTo(totalIncome5)>=0 && fdjtPercent>0){
                if(fdjtPercent>=siteConfig.getInt("orderPercent5")){
                    profit=productTotalPrice.multiply(orderPercent5);
                    fdjtPercent=fdjtPercent-siteConfig.getInt("orderPercent5");
                }else{
                    profit=productTotalPrice.multiply(new BigDecimal(fdjtPercent));
                    fdjtPercent=0;
                }
                memberLevel=5;
            }else if (totaIncome.compareTo(totalIncome4)>=0 && fdjtPercent>0){
                if(fdjtPercent>=siteConfig.getInt("orderPercent4")){
                    profit=productTotalPrice.multiply(orderPercent4);
                    fdjtPercent=fdjtPercent-siteConfig.getInt("orderPercent4");
                }else{
                    profit=productTotalPrice.multiply(new BigDecimal(fdjtPercent));
                    fdjtPercent=0;
                }
                memberLevel=4;
            }else if (totaIncome.compareTo(totalIncome3)>=0 && fdjtPercent>0){
                if(fdjtPercent>=siteConfig.getInt("orderPercent3")){
                    profit=productTotalPrice.multiply(orderPercent3);
                    fdjtPercent=fdjtPercent-siteConfig.getInt("orderPercent3");
                }else{
                    profit=productTotalPrice.multiply(new BigDecimal(fdjtPercent));
                    fdjtPercent=0;
                }
                memberLevel=3;
            }else if (totaIncome.compareTo(totalIncome2)>=0 && fdjtPercent>0){
                if(fdjtPercent>=siteConfig.getInt("orderPercent2")){
                    profit=productTotalPrice.multiply(orderPercent2);
                    fdjtPercent=fdjtPercent-siteConfig.getInt("orderPercent2");
                }else{
                    profit=productTotalPrice.multiply(new BigDecimal(fdjtPercent));
                    fdjtPercent=0;
                }
                memberLevel=2;
            }else if (totaIncome.compareTo(totalIncome1)>=0 && fdjtPercent>0){
                if(fdjtPercent>=siteConfig.getInt("orderPercent1")){
                    profit=productTotalPrice.multiply(orderPercent1);
                    fdjtPercent=fdjtPercent-siteConfig.getInt("orderPercent1");
                }else{
                    profit=productTotalPrice.multiply(new BigDecimal(fdjtPercent));
                    fdjtPercent=0;
                }
                memberLevel=1;
            }
            //存入会员分层金额
            if(profit.compareTo(new BigDecimal(0))>0){
                CustomerAllowance.saveInfo(memberId,totaIncome,profit,0,memberLevel,orderSn,uid);
            }
            if(fdjtPercent<=0){
                break;//辅导津贴百分比小于等于零时,结束循环体,不再对下一个上级会员进行分成
            }

            //查询该会员的总收入额
        }
    }


    //总收入(佣金+培养津贴+辅导津贴)
    public BigDecimal getTotalIncome(String memberId){
        String expectSql="select sum(backmoney)totaIncome from(\n" +
                "SELECT  IFNULL(sum(money),0)backmoney FROM `mall_backmoney` where uid='"+memberId+"' and type = 'FX' \n" +
                "UNION ALL\n" +
                "SELECT  IFNULL(sum(profit),0)backmoney FROM `mall_customer_dividend` where mid='"+memberId+"' \n" +
                "UNION ALL \n" +
                "SELECT IFNULL(sum(profit),0)backmoney FROM `mall_customer_allowance` where mid='"+memberId+"' \n" +
                ")as totaIncome";
        //Record record= Db.findFirst(expectSql);
        BigDecimal totaIncome= Db.queryColumn(expectSql);
        return totaIncome;
    }
}
